local class = reload("class")

---@组队模块
local this = class()

function this:ctor(max)
    self._max = max or 5
    self:clear()
end

function this:clear()
    ---队伍映射{[cdkey] = lcdkey}
    ---@type table<number, number>
    self._partyCdkeys = {}
    ---队伍成员{[lcdkey] = {[cdkey] = lcdkey}}
    ---@type table<number, table>
    self._partyMember = {}
    ---队伍数量{[lcdkey] = number}
    ---@type table<number, number>
    self._partyNumber = {}
end

---登出处理
function this:logout(cdkey)
    self:leave(cdkey)
end

---创建队伍
function this:create(lcdkey)
    if self._partyCdkeys[lcdkey] then
        return false
    end

    local members = self._partyMember[lcdkey] or {}
    self._partyMember[lcdkey] = members
    self:join(lcdkey, lcdkey)
    return true
end

---转让队长
function this:toLeader(lcdkey, cdkey)
    local members = self._partyMember[lcdkey]
    if not members then
        return false
    end

    self._partyMember[lcdkey] = nil
    self._partyMember[cdkey] = members 
    return true
end

---加入队伍
function this:join(lcdkey, cdkey)
    local count = self._partyNumber[lcdkey] or 0
    if count >= self._max then
        return false
    end

    ---成员映射
    local members = self._partyMember[lcdkey]
    if members[cdkey] then
        return false
    end
    members[cdkey] = lcdkey

    ---队伍数量
    self._partyNumber[lcdkey] = count + 1
end

---离开队伍
function this:leave(cdkey)
    local lcdkey = self._partyCdkeys[cdkey]
    if not lcdkey then
        return false
    end

    ---队长只能解散
    if lcdkey == cdkey then
        return false
    end

    ---队员映射
    local members = self._partyMember[lcdkey]
    members[cdkey] = nil

    ---队员数量
    local count = self._partyNumber[lcdkey]
    self._partyNumber[lcdkey] = count - 1
end

---踢人
function this:kick(cdkey)
    return self:leave(cdkey)
end

---解散
function this:disband(lcdkey)
    local members = self._partyMember[lcdkey]
    if not members then
        return false
    end

    for cdkey, _ in pairs(members) do
        self:leave(cdkey)
    end
    return true
end

return this
